package cn.bitkit.component.log;

import com.alibaba.fastjson2.filter.ValueFilter;
import cn.bitkit.base.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Collection;

@Slf4j
public class LogSimplifyFilter implements ValueFilter {

    @Override
    public Object apply(Object object, String name, Object value) {
        if(object == null) {
            return null;
        }
        try {
            if(value instanceof MultipartFile file) {
                return "[MultipartFile:"+file.getOriginalFilename()+"]";
            }
            if(value instanceof File file) {
                return "[File:"+file.getName()+"]";
            }
            if(value instanceof String) {
                int max = 1000;
                if(value.toString().length() > max){
                    return StringUtil.maxLength(value.toString(), max) + "[String length greater than 1000]";
                }
            }
            if(value instanceof Collection<?> co) {
                int max = 100;
                if(co.size() > max){
                    return String.format("[Collection size greater than %d. size = %d]", max, co.size());
                }
            }
            if(value instanceof byte[] bytes){
                return String.format("[byte array size = %d]", bytes.length);
            }
            return value;
        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }
}
